package cn.xueden.service;

import cn.xueden.domain.Order;
import cn.xueden.dto.OrderQueryCriteria;
import cn.xueden.repository.OrderRepository;
import cn.xueden.utils.PageUtil;
import cn.xueden.utils.QueryHelp;
import cn.xueden.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

/**
 * @Auther:梁志杰
 * @Date:2021/5/16
 * @Description:cn.xueden.service
 * @version:1.0
 */
@Service
public class OrderService {

   @Autowired
   private  OrderRepository orderRepository;





    /**
     * 根据订单编号查询订单
     * @param outTradeNo
     * @return
     */
    public Order getByOutTradeNo(String outTradeNo) {
        Order tempOrder = new Order();
        tempOrder.setOutTradeNo(outTradeNo);
        Example<Order> example = Example.of(tempOrder);
        return orderRepository.findOne(example).orElseGet(Order::new);
    }

    /**
     * 更新订单
     * @param dbOrder
     */
    public void saveAndUpdate(Order dbOrder) {
        orderRepository.save(dbOrder);
    }

    /**
     * 分页获取订单列表
     * @param criteria
     * @param pageable
     * @return
     */
    public Object getList(OrderQueryCriteria criteria, Pageable pageable) {
        Page<Order> page = orderRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page);
    }

    /**
     * 添加订单记录
     * @param resources
     */
    public void create(Order resources) {
        // 生成订单编号
        String outTradeNo = StringUtils.createOrderNumber();
        resources.setStatus(0);
        resources.setOutTradeNo(outTradeNo);
        orderRepository.save(resources);
    }

    /**
     * 添加订单记录
     * @param resources
     */
    public void apicreate(Order resources) {
        resources.setStatus(0);
        orderRepository.save(resources);
    }

    /**
     * 根据订单ID获取订单详情
     * @param id
     * @return
     */
    public Order getById(Long id) {
        return orderRepository.findById(id).orElseGet(Order::new);
    }


}
